package com.kun.companion.core.ui.list;

import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;

/**
 * TODO
 *
 * @author gzc
 * @since 2025/2/9 19:09
 **/
public class UserListView extends BaseListView<User> {
    public UserListView() {
        setCellFactory(lv -> new UserListCell());
    }

    public static class UserListCell extends BaseListCell<User> {
        private final ImageView avatarView = new ImageView();
        private final Label nameLabel = new Label();
        private final StackPane statusIndicator = new StackPane();
        private String fileCSS = """
                              .online {
                              -fx-background-color: #4dabf7;
                              }
                              .offline {
                              -fx-background-color: red;
                              }
                """;

        @Override
        protected void initStyle() {
            super.initStyle();
            getStyleClass().add("user-list-cell");
            getStylesheets().add("data:text/css;charset=UTF-8," + fileCSS);

            // 初始化布局样式
            avatarView.setFitWidth(20);
            avatarView.setFitHeight(20);
            statusIndicator.setPrefSize(10, 10);
            statusIndicator.getStyleClass().add("status-indicator");
        }

        @Override
        protected void bindData(User user) {
            // 异步加载头像
            loadAvatarAsync(user.getAvatarUrl());

            nameLabel.setText(user.getName());
            updateStatus(user.isOnline());

            HBox container = new HBox(10, avatarView, nameLabel, statusIndicator);
            setGraphic(container);
        }

        private void updateStatus(boolean online) {
            statusIndicator.getStyleClass().removeAll("online", "offline");
            statusIndicator.getStyleClass().add(online ? "online" : "offline");
        }

        private void loadAvatarAsync(String url) {
            // 使用后台线程加载图片
            new Thread(() -> {
                Image img = new Image("/app-icon.png", true);
                Platform.runLater(() -> avatarView.setImage(img));
            }).start();
        }
    }
}

